<template>
  <div class="dynamic_form_item">
    <a-form-item :name="props.question.key">
      <template v-slot:label>
        <label for="">{{ props.question.label }}</label>
      </template>
      
      <div class="isView" v-if="props.config?.isView">
        <span v-if="props.question.state.labelKey">{{ showKeyName(props.dataForm, props.question.state.labelKey) }}</span>
        <span v-else>{{ props.question.value }}</span>
      </div>
      <a-cascader v-else ref="cascaderAddr" 
        @change="cascaderChange" 
        :placement="props.question.state?.placement || 'bottomLeft'"
        :changeOnSelect="props.question.state.changeOnSelect ? true : false"
        :multiple="props.question.state.multiple || false" 
        :fieldNames="props.question.state.names"
        :options="props.question.options" 
        v-model:value="props.question.value" 
        :disabled="props.question.disabled"
        :show-search="props.question.state.isSearch ? { searchFilter } : false"
        :load-data="loadData"
        :displayRender="displayRender"
        :expand-trigger="props.question.state?.expandTrigger||'hover'"
        style="width:100%">
        <template #displayRender="{ labels, selectedOptions }" v-if="props.config?.isView">
          {{ createVNode(labels) }}
        </template>
      </a-cascader>

    </a-form-item>
  </div>
</template>
<script setup lang="ts">
import { watch, getCurrentInstance, onMounted, onUnmounted, render, h } from "vue";
import { QuestionBase } from "../../../question-base";
import { Subscription } from 'rxjs';
import addressDataJson from '@/json/addressData.json'
import { CASADERSERVE, INITSERVE, RESETVERIFY } from "@/mixins/subject/subject-types";
import { filter } from "rxjs/operators";
import type { ShowSearchType } from 'ant-design-vue/es/cascader';
import {  paramsData, showKeyName } from '@/components/public-template/publicMethod';
import { formInfoStore } from '@/store/modules/form';
import { findObjectByIdInArray } from "@/utils";
const formStore = formInfoStore();

//subject变量
let $subscribeSub: Subscription;
let areaData:any;

const { proxy  }:any = getCurrentInstance()
let props = defineProps<{ question: QuestionBase<any>,formData:any; config?: any; dataForm?: any; }>();
const emit = defineEmits([ "update:formData"]);
watch(()=>props.question.value, (val)=>{
    emit('update:formData', val);
},{ flush:'sync' })

onMounted(() => { 
  init();
  subWatch(); 
})

//解绑
onUnmounted(() => {
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
});
function displayRender(arg){
  if (arg.selectedOptions.length > 0 && arg.selectedOptions[0] == null) {
    return props.question.state.labelKey ? showKeyName(props.dataForm, props.question.state.labelKey) : props.question.value;
  }
  return arg.labels.join(' / ');
}
function init(){
  
  //初始化key名
    if (!props.question.state.names) {
      props.question.state.names = {
        value: 'value',
        children: 'children',
        label: 'label',
      };
    }
    //自动省市区
    if (props.question.type === 'area') {
      areaData = addressDataJson;
      props.question.options = JSON.parse(areaData.Data);
    }
    if( props.question.state.url ){
      initData();
    }
}
// 初始化数据
function initData() {
  let params = Object.assign({},props.question.state.params ||{})
  proxy.$Http.api(props.question.state.url, params, props.question.state.protType ? props.question.state.protType : 'get').then((data: any) => {
    if( data ){
      if (props.question.state.initData) {
        props.question.options = props.question.state.initData(data.data);
      } else {
        props.question.options = data.data;
      }
    }
  });
}
// 点击节点，加载子节点数据（需要配置有state.loadData）
function loadData(selectedOptions){
  const targetOption = selectedOptions[selectedOptions.length - 1];
  if(props.question.state.loadData){
    let params = Object.assign({}, props.question.state.params || {});
    if (props.question.state.paramsFormat) { Object.assign(params, props.question.state.paramsFormat(targetOption)); }
    proxy.$Http.api(props.question.state.url, params, props.question.state.protType ? props.question.state.protType : 'get').then((data: any) => {
      targetOption[props.question.state.names.children] = props.question.state.loadData(data.data);
      targetOption.isLeaf = targetOption[props.question.state.names.children].length == 0;
    });
  }
}

//选择灵动
function cascaderChange(value:any, selectedOptions:any) {
  props.question.state.labels = selectedOptions.map((res: any) => res[props.question.state.names.label]);
  if(props.question.state.changeWithMethod){
    if(props.question.state.changeWithMethod(value, selectedOptions)==false){
      // 若节点不允许被选择，则执行清理
      if(props.question.state.multiple){
        // 多选暂未处理
      } else {
        props.question.value = [];
      }
    }
  }


  //控制form参数
  if (props.question.state && props.question.state.changeOptions && !props.question.hidden) {
    updateOptions(props.question.state.changeOptions[props.question.value] || props.question.state.changeOptions['default']);
  }
  //自动灵动更新同级组件属性并初始化
  if (props.question.state.changeAuto && props.question.value !== null) {
    let data:any ={};
    
    data = findObjectByIdInArray(props.question.options, props.question.value[props.question.value.length -1], 'id', props.question.state.names.children)

    let options = [];
    if (data && !props.question.state.offChangeAuto &&  props.question.value) {
      if( Array.isArray(props.question.state.changeAuto)  ){
        props.question.state.changeAuto.forEach((item)=>{
          options.push({
              key: item.key,
              option: item.option,
              isAssign : item.isAssign || false,
              value:
              item.isOptionReplace ? replaceOptions(data,item):
                typeof item.value === 'string'
                  ? showKeyName(data, item.value)
                  : paramsData(data, { params: item.value },props.question.value)
            })
        })
      }else{
        for (const key in props.question.state.changeAuto) {
          if (props.question.state.changeAuto[key]) {
            options.push({
              key,
              option: props.question.state.changeAuto[key]?.option || 'state.params',
              isAssign : props.question.state.changeAuto[key].isAssign || false,
              value:
                typeof props.question.state.changeAuto[key].value === 'string'
                  ? showKeyName(data, props.question.state.changeAuto[key].value)
                  : paramsData(data, { params: props.question.state.changeAuto[key].value },props.question.value)
            });
          }
        }
      }
    }
    options.length && updateOptions(options);
    console.log('选中的值', options, data);
  }

  proxy.$NotificationFormSub.pushParams({
    key: CASADERSERVE,
    value: {
      key: props.question.key,
      value: props.question.value,
      state: props.question.state,
    }
  });

  //初始化服务
  if ( props.question.state.initKeys) {
    proxy.$NotificationFormSub.pushParams({
      key: INITSERVE,
      value: {
        initKeys: props.question.state.initKeys,
        isOptionReplace: props.question.state.isOptionReplace,
        name: props.question.state.name || '',
        configName: props.config.name || '',
      }
    });
  }
}

//sdw 替换options
const replaceOptions = (data,item)=>{
  let obj = {};
  for (const key in item.value) {
    obj[key] = showKeyName(data, item.value[key]);
  }
  return [obj]
}

//更新云数据
const updateOptions = (arr: any = []) => {
  const formStore = formInfoStore();
  if (props.question.state.type === 'layer' || props.config.type === 'layer') {
    formStore.updateLayerQuestions(arr);
  }
  formStore.updateQuestions(arr);
  //动态改变表单
  proxy.$NotificationFormSub.pushParams({ key: RESETVERIFY, value: { name: 'form' } });
};


//监听动态表单数据完成
const subWatch = () => {
  $subscribeSub = proxy.$NotificationFormSub
    .getParams()
    .pipe(filter((res: any) => res !== 0))
    .subscribe((item: any) => {
      try {
        //联动同类型的初始化
        if (item.key == INITSERVE && item.value.initKeys.includes(props.question.key) && ((props.config.name && props.config.name === item.value.configName) || !props.config.name)) {
          console.log('cascaderinit',item);
          if( !item.value.isOptionReplace ){
            init();
          }
        }
      } catch (error) { }
    });
};


function createVNode(labels) {
  if (document.querySelector('.isViewText')) {
    document.querySelector('.isViewText').parentNode.removeChild(document.querySelector('.isViewText'))
  }

  const createSpan = document.createElement('span');
  createSpan.classList.add('isViewText');
  const vnode = h('text', {}, labels.join('/'));

  document.querySelector('.isView').appendChild(createSpan);
  render(vnode, createSpan)
}

// 搜索选项
const searchFilter: ShowSearchType['filter'] = (inputValue, path) => {
  return path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};

</script>


<style lang="less" scoped>
@import url('./input-cascader.component.less');
</style>
